
#include <cstdio>
#include "member_BSerialPort.h"

using namespace BWE;

member_BSerialPort::member_BSerialPort(BSerialPort* serialPort)
{
	boss = serialPort;
	mode = BSerialPort::ModeNone;
	baudRate = BSerialPort::BaudNone;
	dataBits = BSerialPort::DataNone;
	direction = BSerialPort::DirectNone;
	flowControl = BSerialPort::FlowNone;
	parity = BSerialPort::ParityNone;
	stopBits = BSerialPort::StopNone;
#ifdef _WINDOWS_SYSTEM_
	hcom = INVALID_HANDLE_VALUE;
#endif
}
member_BSerialPort::~member_BSerialPort()
{

}

void member_BSerialPort::freshComState()
{
	if (hcom == INVALID_HANDLE_VALUE)
		return;
	DCB dcb;
	GetCommState(hcom, &dcb);
	dcb.BaudRate = baudRate;
	dcb.fBinary = true;
	if (parity == BSerialPort::ParityNone)
		dcb.fParity = false;
	else
		dcb.fParity = true;
	dcb.ByteSize = dataBits;
	switch (parity)
	{
	case BSerialPort::ParityOdd:
		dcb.Parity = ODDPARITY;
		break;
	case BSerialPort::ParityEven:
		dcb.Parity = EVENPARITY;
		break;
	case BSerialPort::ParityMark:
		dcb.Parity = MARKPARITY;
		break;
	case BSerialPort::ParitySpace:
		dcb.Parity = SPACEPARITY;
		break;
	default:
		dcb.Parity = 0;
	}
	switch (stopBits)
	{
	case BSerialPort::StopOne:
		dcb.StopBits = ONESTOPBIT;
		break;
	case BSerialPort::StopOneAndHalf:
		dcb.StopBits = ONE5STOPBITS;
		break;
	case BSerialPort::StopTwo:
		dcb.StopBits = TWOSTOPBITS;
		break;
	default:
		dcb.StopBits = ONESTOPBIT;
	}
	SetCommState(hcom, &dcb);
}

void member_BSerialPort::checkError()
{
	const char* errorStr = 0;
#ifdef _WINDOWS_SYSTEM_
	DWORD error = GetLastError();
	switch (error)
	{
	case ERROR_FILE_NOT_FOUND:
		errorStr = "SerialPort cannot be found.";
		break;

	case ERROR_INVALID_PARAMETER:
		errorStr = "SerialPort parameter is invalid.";
		break;
	}
#endif
	printf("%s : %s\n", portName.cstr(), errorStr);
}